const tryCatch = require('../../utils/tryCatch');
const {
  ServerCreateGroup,
  ServerGetGroupMessageById,
  ServerGetGroupInfoById,
  ServerChangeCommendName,
  ServerUnentryUser,
  ServerUpdataGroupname
} = require("../../server/group/index")
const { ServerGetUserSockIdlistByIDList } = require("../../server/user")
const { Private } = require("../../server/message")
const socket = require("../socket/initSocket")
const userGroup = require("../../model/userGroup")
const groupMessage = require("../../model/groupMessage")
const userGroupMessage = require("../../model/userGroupMessage")
const MessageType = require("../../constants/MessageType")
const UserInfo = require("../../model/userinfo")

const Group = {
  CreatedGroup: tryCatch(async (req, res) => {
    if (req.body.userList?.length && req.body.userName, req.body.groupCreatorId) {
      const userIdList = req.body.userList.map(item => item.id);
      const CreateGroupres = await ServerCreateGroup(req.body.groupCreatorId, req.body.userName, userIdList)
      if (CreateGroupres.isok) {
        const socketRoom = CreateGroupres.data.groupRoom;
        try {
          const socketlistres = await ServerGetUserSockIdlistByIDList(userIdList)
          if (socketlistres.isok) {
            const socketidlist = socketlistres.data.map(item => item.socketid);
            socketidlist.forEach(socketid => {
              if (socketid && socket.io.sockets.sockets.get(socketid)) {
                socket.io.sockets.sockets.get(socketid).join(socketRoom); // 将指定的 socket 加入到房间
              }
            });
            const welcomeMessageid = CreateGroupres.userGroupMessagelist[0].messageLastdate;
            const groupMessageRes = await ServerGetGroupMessageById(welcomeMessageid);
            if (groupMessageRes.isok) {
              console.log("userName " + req.body.userName + " 创建了群聊 ");
              socket.io.to(socketRoom).emit("creategroup", {
                id: CreateGroupres.data.id,
                message: groupMessageRes.data.messageContent,
                lastMessageTime: groupMessageRes.data.createdAt,
                name: CreateGroupres.data.groupName,
                avatar: CreateGroupres.data.groupAvatar,
                noMessageNum: 1,
                type: "group"
              })
            }
          }
        } catch (error) {
          console.log(error);
        }
        res.send({
          statusCode: 200,
          data: CreateGroupres.data
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "创建失败",
          data: false
        })
      }
      //将列表人员添加到socket的房间中,然后将在群聊里面的人发送系统消息 xxx已经创建群聊快来聊天吧
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  GetGroupInfo: tryCatch(async (req, res) => {
    const { messageId, userId } = req.body
    if (messageId && userId) {
      const GetGroupInfoByIdres = await ServerGetGroupInfoById(messageId, userId)
      if (GetGroupInfoByIdres.isok) {
        res.send({
          statusCode: 200,
          data: GetGroupInfoByIdres.data
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "获取失败",
          data: {}
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  ChangeCommendName: tryCatch(async (req, res) => {
    const { type, userId, groupId } = req.body
    if (type && userId && groupId) {
      const GetGroupInfoByIdres = await ServerChangeCommendName({ type, userId, groupId, groupName: req.body.groupName, userCommendName: req.body.userCommendName })
      if (GetGroupInfoByIdres.isok) {
        res.send({
          statusCode: 200,
          data: GetGroupInfoByIdres.data
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "获取失败",
          data: {}
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  UnentryUser: tryCatch(async (req, res) => {
    const { userId, groupId } = req.body
    if (userId && groupId) {
      const GetGroupInfoByIdres = await ServerUnentryUser({ userId, groupId })
      if (GetGroupInfoByIdres.isok) {
        if (GetGroupInfoByIdres.type) {
          ServerGetUserSockIdlistByIDList(GetGroupInfoByIdres.data).then((socketListres) => {
            const socketlist = socketListres.data.map(item => item.socketid);
            socketlist.forEach(socketid => {
              socket.io.to(socketid).emit("destroygroup", {
                isok: 1
              })
            })
          })
        }
        res.send({
          statusCode: 200,
          data: GetGroupInfoByIdres.data
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: GetGroupInfoByIdres.message,
          data: {}
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  ResetGroupName: tryCatch(async (req, res) => {
    const groupId = req.body.groupId
    if (groupId) {
      const updataGroupname = await ServerUpdataGroupname({ groupId, name: req.body.name });
      if (updataGroupname.isok) {
        res.send({
          statusCode: 200,
          data: updataGroupname.data
        })
      } else {
        res.send({
          statusCode: 403,
          errorInfo: "修改失败",
          data: {}
        })
      }
    } else {
      res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      })
    }
  }),
  AddUsersToGroup: tryCatch(async (req, res) => {
    const { groupId, userList, userId } = req.body;

    if (!groupId || !userList || !userList.length || !userId) {
      return res.send({
        statusCode: 403,
        errorInfo: "参数错误",
        data: false
      });
    }

    try {
      // 查询群信息，确认当前用户是否为群主
      const groupInfo = await userGroup.findOne({
        where: {
          id: groupId
        }
      }, { raw: true });

      if (!groupInfo) {
        return res.send({
          statusCode: 403,
          errorInfo: "群聊不存在",
          data: false
        });
      }

      // 验证当前用户是否为群主
      if (groupInfo.groupCreatorId !== userId) {
        return res.send({
          statusCode: 403,
          errorInfo: "只有群主可以添加成员",
          data: false
        });
      }

      // 获取最新的系统消息，作为新用户的最后消息ID
      const latestMessage = await groupMessage.findOne({
        where: {
          groupId: groupId
        },
        order: [['createdAt', 'DESC']]
      }, { raw: true });

      if (!latestMessage) {
        return res.send({
          statusCode: 403,
          errorInfo: "获取群消息失败",
          data: false
        });
      }

      // 获取当前群内所有用户的ID
      const existingGroupUsers = await userGroupMessage.findAll({
        where: {
          groupId: groupId
        },
        attributes: ['userId']
      }, { raw: true });

      const existingUserIds = existingGroupUsers.map(user => user.userId);

      // 过滤掉已经在群内的用户
      const newUserIds = userList.filter(id => !existingUserIds.includes(id));

      if (!newUserIds.length) {
        return res.send({
          statusCode: 403,
          errorInfo: "所选用户已在群内",
          data: false
        });
      }

      // 获取操作者（邀请者）的用户信息
      const inviterUserInfo = await UserInfo.findOne({
        where: { id: userId }
      }, { raw: true });

      if (!inviterUserInfo) {
        return res.send({
          statusCode: 403,
          errorInfo: "操作用户信息获取失败",
          data: false
        });
      }

      // 准备新用户的群组关联数据
      const userGroupData = newUserIds.map(id => ({
        userId: id,
        groupId: groupId,
        groupName: '',
        messageLastdate: latestMessage.id,
        noMessageNum: 1
      }));

      // 创建用户与群的关联
      const result = await userGroupMessage.bulkCreate(userGroupData);

      if (!result.length) {
        return res.send({
          statusCode: 403,
          errorInfo: "添加用户失败",
          data: false
        });
      }

      // 更新群聊人数和用户ID列表
      const currentUserIds = groupInfo.userIdList ? groupInfo.userIdList.split(',') : [];
      const allUserIds = [...currentUserIds, ...newUserIds].filter(Boolean);

      await userGroup.update({
        groupNumber: allUserIds.length,
        userIdList: allUserIds.join(',')
      }, {
        where: {
          id: groupId
        }
      });

      // 获取socket信息将新用户加入房间并发送邀请消息
      try {
        const socketlistres = await ServerGetUserSockIdlistByIDList(newUserIds);
        if (socketlistres.isok) {
          const socketidlist = socketlistres.data.map(item => item.socketid);
          socketidlist.forEach(socketid => {
            if (socketid && socket.io.sockets.sockets.get(socketid)) {
              const targetSocket = socket.io.sockets.sockets.get(socketid);
              targetSocket.join(groupInfo.groupRoom);
              // 发送被邀请进群的socket消息
              targetSocket.emit(MessageType.INVITED_TO_GROUP, {
                id: groupInfo.id,
                name: groupInfo.groupName,
                avatar: groupInfo.groupAvatar,
                message: `${inviterUserInfo.userName || '用户'} 邀请您加入群聊: ${groupInfo.groupName}`,
                lastMessageTime: new Date().toISOString(),
                noMessageNum: 1,
                type: "group"
              });
            }
          });
        }
      } catch (error) {
        console.log("将用户加入socket房间或发送邀请消息失败:", error);
      }

      res.send({
        statusCode: 200,
        message: "添加用户成功",
        data: {
          addedUserIds: newUserIds,
          groupId: groupId
        }
      });
    } catch (error) {
      console.error("添加用户到群聊出错:", error);
      res.send({
        statusCode: 500,
        errorInfo: "服务器错误",
        data: false
      });
    }
  })
}

module.exports = {
  CreatedGroup: Group.CreatedGroup,
  GetGroupInfo: Group.GetGroupInfo,
  ChangeCommendName: Group.ChangeCommendName,
  UnentryUser: Group.UnentryUser,
  ResetGroupName: Group.ResetGroupName,
  AddUsersToGroup: Group.AddUsersToGroup
};